
#include "communication.h"
#include "sys.h"
#include "sense_485.h"
#include "common.h"
#include "config.h"

int SenseRequest(uint8_t *addr,uint8_t function, TickType_t pportMAX_DELAY)
{
	uint8_t aucSenseCom_Buffer[20],i;
	uint16_t CrcData;
	aucSenseCom_Buffer[0] = addr[0];
	aucSenseCom_Buffer[1] = addr[1];
	aucSenseCom_Buffer[2] = function;
	aucSenseCom_Buffer[3] = 0x07;
	aucSenseCom_Buffer[4] = SENSE_MODBUS_REV;
	CrcData = MBCrcCheck(aucSenseCom_Buffer, 5);
	aucSenseCom_Buffer[5] = CrcData >> 8;
	aucSenseCom_Buffer[6] = CrcData;
	for(i = 0; i < 4;i++)
	{
		aucSenseCom_Buffer[7+i] = 0xFE;
	}
	return Sense485Send(aucSenseCom_Buffer, 11, pportMAX_DELAY);
}



int SenseData(uint8_t *addr,uint8_t function,uint8_t *SenseValue, TickType_t pportMAX_DELAY)
{
	uint16_t Addrtemp,Addr;
	uint32_t uiSenseData;
	uint8_t pBuffer[100];
	uint8_t uclen;
//	uint8_t i;
	
	Addr = addr[0] << 8 | addr[1];
	if(Sense485Rece(pBuffer, &uclen, pportMAX_DELAY))
	{
		if(uclen > 6)
		{
			if(ReceCrcCheck(pBuffer,uclen - 4))
			{
				Addrtemp = (pBuffer[0] << 8) | pBuffer[1];
				if((Addrtemp == Addr)&&(pBuffer[2] == 0xFF))
				{
					if((pBuffer[4] == function)&&(pBuffer[5] == 0x00))
					{
						switch(pBuffer[4])
						{
							case SENSE_COM_VIBRATOR_FUNCTION:
										SenseValue[0] = pBuffer[7];
										SenseValue[1] = pBuffer[8];
										SenseValue[2] = pBuffer[9];
										SenseValue[3] = pBuffer[10];
										SenseValue[4] = pBuffer[11];
										SenseValue[5] = pBuffer[12];
										SenseValue[6] = pBuffer[14];
										SenseValue[7] = pBuffer[15];
										SenseValue[8] = pBuffer[16];
										SenseValue[9] = pBuffer[17];
										SenseValue[10] = pBuffer[18];
										SenseValue[11] = pBuffer[19];
										break;
							case SENSE_COM_INFRARED_FUNCTION:
										uiSenseData = ((pBuffer[6] << 8) | pBuffer[7]);
										SenseValue[0] = uiSenseData >> 8;
										SenseValue[1] = uiSenseData;		
										break;
						}
						return 0;
					}
				}
			}
		}
	}
	return -1;
}

